import { useState, useContext, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { AuthContext } from '@/contexts/authContext';
import { Toaster, toast } from 'sonner';
import { Heart, Trash2, RefreshCw, Brain, Sparkles, Star } from 'lucide-react';

// 定义故事数据类型
interface Story {
  id: string;
  title: string;
  description: string;
  pageCount: number;
  date: string;
  isCollected: boolean;
}

// 定义推荐故事数据类型
interface RecommendedStory {
  id: string;
  title: string;
  description: string;
  relevance: number;
  pageCount: number;
  theme?: string;
}

export default function CollectionPage() {
  const { isAuthenticated, currentUser } = useContext(AuthContext);
  const navigate = useNavigate();
  
  // 收藏的故事数据
  const [collectedStories, setCollectedStories] = useState<Story[]>([]);
  const [loading, setLoading] = useState(true);
  const [recommendedStories, setRecommendedStories] = useState<RecommendedStory[]>([]);
  const [isGeneratingRecommendations, setIsGeneratingRecommendations] = useState(false);
  
  // 检查用户是否已认证并加载收藏的故事
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
      return;
    }
    
    loadCollectedStories();
  }, [isAuthenticated, navigate]);
  
  // 加载收藏的故事
  const loadCollectedStories = () => {
    setLoading(true);
    
    try {
      // 从localStorage中获取收藏的故事
      const savedCollections = localStorage.getItem('collectedStories');
      
      if (savedCollections) {
        const parsedStories: Omit<Story, 'isCollected'>[] = JSON.parse(savedCollections);
        
        // 去重处理 - 根据id确保故事唯一性
        const uniqueStories = Array.from(new Map(parsedStories.map(story => [story.id, story])).values());
        
        // 添加isCollected属性
        const storiesWithStatus = uniqueStories.map(story => ({
          ...story,
          isCollected: true
        }));
        
        setCollectedStories(storiesWithStatus);
        
        // 如果有收藏的故事，生成推荐
        if (storiesWithStatus.length > 0) {
          generateRecommendations(storiesWithStatus);
        }
      } else {
        // 如果没有保存的收藏，使用默认数据
        setCollectedStories(getDefaultCollectionStories());
        
        // 生成推荐
        generateRecommendations(getDefaultCollectionStories());
      }
    } catch (error) {
      console.error('Failed to load collected stories:', error);
      toast('加载收藏故事失败，请稍后再试');
      // 加载默认数据作为备选
      setCollectedStories(getDefaultCollectionStories());
      generateRecommendations(getDefaultCollectionStories());
    } finally {
      setLoading(false);
    }
  };
  
  // 监听localStorage变化，确保在其他标签页修改收藏时能同步更新
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'collectedStories') {
        loadCollectedStories();
      }
    };
    
    window.addEventListener('storage', handleStorageChange);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);
  
  // 获取默认的收藏故事数据（用于首次访问或加载失败时）
  const getDefaultCollectionStories = (): Story[] => {
    return [
      {
        id: '2',
        title: '魔法森林的秘密',
        description: '小熊在森林深处发现了一个神秘的魔法门，门后隐藏着会说话的树木、会跳舞的花朵和需要帮助的森林精灵们。',
        pageCount: 7,
        date: '2025/10/2',
        isCollected: true
      },
      {
        id: '1',
        title: '小狐狸的星空冒险',
        description: '在一个宁静的夜晚，小狐狸发现了一颗会说话的星星。星星告诉小狐狸，今晚是星空王国一年一度的庆典，邀请它一起去参加。',
        pageCount: 7,
        date: '2025/10/2',
        isCollected: true
      },
      {
        id: '3',
        title: '彩虹桥上的友谊',
        description: '小兔子和小松鼠在彩虹桥上相遇，他们一起克服暴风雨的挑战，学会了互相帮助和分享的重要性。',
        pageCount: 6,
        date: '2025/10/2',
        isCollected: true
      },
      {
        id: '4',
        title: '海底城堡大探险',
        description: '小海豚和小海龟组成探险队，在珊瑚迷宫中寻找古老的海底宝藏，同时要避开调皮的海胆和饥饿的海怪。',
        pageCount: 8,
        date: '2025/10/2',
        isCollected: true
      }
    ];
  };
  
  // 基于用户收藏生成推荐故事
  const generateRecommendations = (stories: Story[]) => {
    setIsGeneratingRecommendations(true);
    
    // 模拟AI推荐过程
    setTimeout(() => {
      // 分析用户收藏的主题
      const themes: Record<string, number> = {};
      stories.forEach(story => {
        // 简单的主题提取逻辑（实际应用中可能需要NLP分析）
        const title = story.title.toLowerCase();
        if (title.includes('魔法')) themes['魔法'] = (themes['魔法'] || 0) + 1;
        if (title.includes('星空')) themes['星空'] = (themes['星空'] || 0) + 1;
        if (title.includes('友谊')) themes['友谊'] = (themes['友谊'] || 0) + 1;
        if (title.includes('海底')) themes['海底'] = (themes['海底'] || 0) + 1;
        if (title.includes('森林')) themes['森林'] = (themes['森林'] || 0) + 1;
      });
      
      // 找出用户最喜欢的主题
      let favoriteTheme = '奇幻';
      let maxCount = 0;
      Object.entries(themes).forEach(([theme, count]) => {
        if (count > maxCount) {
          maxCount = count;
          favoriteTheme = theme;
        }
      });
      
      // 生成与用户兴趣相关的推荐故事
      const recommendations: RecommendedStory[] = generatePersonalizedRecommendations(favoriteTheme);
      setRecommendedStories(recommendations);
      setIsGeneratingRecommendations(false);
    }, 1500);
  };
  
  // 生成个性化推荐故事
  const generatePersonalizedRecommendations = (favoriteTheme: string): RecommendedStory[] => {
    // 基于主题的推荐库
    const themeRecommendations: Record<string, RecommendedStory[]> = {
      '魔法': [
        {
          id: 'r1',
          title: '魔法学院的新生',
          description: '小猫头鹰露娜进入了神秘的魔法学院，在那里她学习了各种神奇的魔法，并结交了一群好朋友。',
          relevance: 95,
          pageCount: 7,
          theme: '魔法'
        },
        {
          id: 'r2',
          title: '魔法师的学徒',
          description: '小猴子阿明成为了一位老魔法师的学徒，在学习魔法的过程中，他明白了真正的魔法来自内心的善良。',
          relevance: 90,
          pageCount: 6,
          theme: '魔法'
        }
      ],
      '星空': [
        {
          id: 'r1',
          title: '星空魔法师的学徒',
          description: '小猫咪学习星空魔法的成长历程，充满奇幻和智慧的冒险',
          relevance: 92,
          pageCount: 6,
          theme: '星空'
        },
        {
          id: 'r2',
          title: '星际旅行家',
          description: '小狗豆豆乘坐宇宙飞船开始了星际旅行，在旅途中他认识了许多外星朋友，学到了很多知识。',
          relevance: 88,
          pageCount: 7,
          theme: '星空'
        }
      ],
      '友谊': [
        {
          id: 'r1',
          title: '彩虹桥的守护者',
          description: '小兔子守护彩虹桥的温暖故事，教会孩子们珍惜友谊和保护自然',
          relevance: 94,
          pageCount: 6,
          theme: '友谊'
        },
        {
          id: 'r2',
          title: '最好的朋友',
          description: '小松鼠和小刺猬成为了最好的朋友，他们一起度过了许多快乐的时光，也一起克服了许多困难。',
          relevance: 91,
          pageCount: 6,
          theme: '友谊'
        }
      ],
      '海底': [
        {
          id: 'r1',
          title: '海底王国的秘密',
          description: '小美人鱼爱丽儿发现了海底王国的一个古老秘密，她和朋友们一起保护了这个秘密，成为了海底王国的英雄。',
          relevance: 93,
          pageCount: 7,
          theme: '海底'
        },
        {
          id: 'r2',
          title: '珊瑚礁的守护者',
          description: '小海龟汤米和他的朋友们一起保护珊瑚礁，他们努力让珊瑚礁重新变得美丽起来。',
          relevance: 89,
          pageCount: 6,
          theme: '海底'
        }
      ],
      '森林': [
        {
          id: 'r1',
          title: '森林守护者',
          description: '小鹿斑比成为了森林的守护者，他和森林里的动物们一起保护他们的家园，让森林变得更加美丽。',
          relevance: 94,
          pageCount: 7,
          theme: '森林'
        },
        {
          id: 'r2',
          title: '森林里的音乐会',
          description: '森林里的动物们举办了一场盛大的音乐会，每个动物都展示了自己的特长，大家度过了一个快乐的夜晚。',
          relevance: 90,
          pageCount: 6,
          theme: '森林'
        }
      ],
      '奇幻': [
        {
          id: 'r1',
          title: '奇幻王国历险记',
          description: '小熊维尼和他的朋友们来到了一个奇幻王国，在那里他们经历了许多奇妙的冒险。',
          relevance: 91,
          pageCount: 7,
          theme: '奇幻'
        },
        {
          id: 'r2',
          title: '梦境探险者',
          description: '小老鼠米奇发现自己可以进入别人的梦境，他用这个能力帮助了许多有困难的朋友。',
          relevance: 88,
          pageCount: 6,
          theme: '奇幻'
        }
      ]
    };
    
    // 返回与用户最喜欢的主题相关的推荐
    return themeRecommendations[favoriteTheme] || themeRecommendations['奇幻'];
  };
  
  // 移除收藏的故事
  const removeFromCollection = (storyId: string) => {
    try {
      // 更新状态
      setCollectedStories(prevStories => 
        prevStories.filter(story => story.id !== storyId)
      );
      
      // 更新localStorage
      const updatedStories = collectedStories.filter(story => story.id !== storyId);
      localStorage.setItem('collectedStories', JSON.stringify(updatedStories));
      
      toast('已从收藏中移除');
      
      // 如果收藏列表为空，清空推荐
      if (updatedStories.length === 0) {
        setRecommendedStories([]);
      }
    } catch (error) {
      console.error('Failed to remove story from collection:', error);
      toast('移除失败，请稍后再试');
    }
  };
  
  // 刷新推荐
  const refreshRecommendations = () => {
    if (collectedStories.length > 0) {
      toast('正在更新AI推荐...');
      generateRecommendations(collectedStories);
    } else {
      toast('请先收藏一些故事以获取个性化推荐');
    }
  };
  
  // 阅读推荐的故事
  const readRecommendedStory = (recommendedStory: RecommendedStory) => {
    // 为推荐的故事创建一个临时故事对象
    const tempStory = {
      id: recommendedStory.id,
      title: recommendedStory.title,
      description: recommendedStory.description,
      content: generateRecommendedStoryContent(recommendedStory),
      pageCount: recommendedStory.pageCount,
      keywords: [recommendedStory.theme || '奇幻', '冒险', '成长'],
      moral: '勇敢面对困难，珍惜友谊',
      generationTime: 0
    };
    
    // 保存到localStorage，以便在阅读页面加载
    localStorage.setItem('generatedStory', JSON.stringify(tempStory));
    
    // 跳转到阅读页面
    navigate(`/read/${recommendedStory.id}`);
  };
  
  // 生成推荐故事的内容
  const generateRecommendedStoryContent = (story: RecommendedStory): string[] => {
    const content: string[] = [];
    
    for (let i = 1; i <= story.pageCount; i++) {
      let pageContent = '';
      
      if (i === 1) {
        pageContent = `在一个美丽的${story.theme || '奇幻'}世界里，${story.title}的故事开始了。这是一个关于冒险、友谊和成长的故事。`;
      } else if (i === story.pageCount) {
        pageContent = `${story.title}的故事结束了，但他们的冒险精神永远不会结束。通过这次经历，他们明白了许多重要的道理。`;
      } else {
        pageContent = `随着故事的发展，${story.title}遇到了许多有趣的事情和挑战。他们凭借着勇气和智慧，一次又一次地克服了困难。`;
      }
      
      content.push(pageContent);
    }
    
    return content;
  };
  
  // 未登录时不渲染内容
  if (!isAuthenticated) return null;
  
  return (
    <div className="min-h-screen bg-gradient-to-b from-pink-50 to-blue-50 flex flex-col pb-20 text-gray-800">
      <div className="container mx-auto flex-1 flex flex-col">
      <Toaster />
      
      {/* 顶部导航栏 */}
      <header className="bg-white/80 backdrop-blur-md border-b border-pink-100 px-4 py-3 flex justify-between items-center shadow-sm">
        <div className="flex items-center">
          <span className="text-2xl font-bold text-gradient">
            <span className="text-pink-400">✨</span> 智绘童话AI工场
          </span>
        </div>
        <div className="flex items-center space-x-2">
          <span className="text-gray-700">{currentUser || '管理员'}</span>
        </div>
      </header>

      {/* 页面标题 */}
      <section className="px-6 pt-6 pb-4">
        <h1 className="text-2xl font-bold text-gray-800 flex items-center">
          <Heart size={24} className="mr-2 text-pink-500 fill-current" /> 
          我的收藏
        </h1>
      </section>

      {/* 收藏的故事列表 */}
      <section className="px-6 mb-8">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-lg font-semibold text-gray-800">我的收藏故事 ({collectedStories.length})</h2>
        </div>
        
        {loading ? (
          // 加载状态
          <div className="space-y-4">
            {[1, 2, 3].map(i => (
              <div key={i} className="bg-white rounded-xl p-4 border border-pink-100 animate-pulse">
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="h-6 bg-pink-100 rounded w-2/3 mb-2"></div>
                    <div className="h-4 bg-pink-100 rounded w-full mb-1"></div>
                    <div className="h-4 bg-pink-100 rounded w-full mb-3"></div>
                    <div className="flex space-x-3">
                      <div className="h-3 bg-pink-100 rounded w-12"></div>
                      <div className="h-3 bg-pink-100 rounded w-16"></div>
                      <div className="h-3 bg-pink-100 rounded w-20"></div>
                    </div>
                  </div>
                  <div className="flex flex-col items-end">
                    <div className="w-10 h-10 bg-pink-100 rounded-full mb-2"></div>
                    <div className="w-16 h-8 bg-pink-100 rounded-full"></div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <>
            {/* 故事列表 */}
            <div className="space-y-4">
              {collectedStories.map(story => (
                <div key={story.id} className="bg-white rounded-xl p-4 border border-pink-100 hover:border-pink-300 transition-all duration-300 shadow-sm hover:shadow-md card-gradient">
                  <div className="flex justify-between items-start">
                    <div>
                      <h3 className="text-lg font-semibold text-gray-800 flex items-center">
                        <span className="mr-2 text-pink-400">✨</span> {story.title}
                      </h3>
                      <p className="text-gray-500 text-sm mt-1 line-clamp-2">{story.description}</p>
                      <div className="flex items-center mt-2 text-xs text-gray-500">
                        <span className="mr-3">{story.pageCount} 页</span>
                        <span className="mr-3">{story.date}</span>
                        <span className="text-pink-500 flex items-center">
                          <Heart size={12} className="mr-1 fill-current" /> 已收藏
                        </span>
                      </div>
                    </div>
                    <div className="flex flex-col items-end">
                      <button 
                        onClick={() => removeFromCollection(story.id)}
                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                        aria-label="移除收藏"
                      >
                        <Trash2 size={20} />
                      </button>
                      <Link to={`/read/${story.id}`}>
                        <button className="mt-2 bg-gradient-to-r from-pink-100 to-blue-100 text-pink-500 text-sm px-3 py-1 rounded-full hover:from-pink-200 hover:to-blue-200 transition-colors">
                          阅读
                        </button>
                      </Link>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            
            {/* 空收藏提示 */}
            {collectedStories.length === 0 && (
              <div className="bg-white rounded-xl p-8 text-center border border-pink-100 shadow-sm">
                <div className="text-4xl mb-4">❤️</div>
                <h3 className="text-lg font-medium text-gray-800 mb-2">还没有收藏任何故事</h3>
                <p className="text-gray-500 text-sm mb-4">去首页或生成页面发现并收藏喜欢的故事吧</p>
                <Link to="/home">
                  <button className="bg-gradient-to-r from-pink-100 to-blue-100 text-pink-500 px-4 py-2 rounded-lg hover:from-pink-200 hover:to-blue-200 transition-colors">
                    浏览故事
                  </button>
                </Link>
              </div>
            )}
          </>
        )}
      </section>

      {/* 为您推荐 */}
      {collectedStories.length > 0 && (
        <section className="px-6 mb-8">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-gray-800 flex items-center">
              <span className="mr-2 text-pink-400">🔍</span> 为您推荐
            </h2>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-500">个性化</span>
              <button 
                onClick={refreshRecommendations}
                disabled={isGeneratingRecommendations}
                className={`p-1 ${isGeneratingRecommendations ? 'text-gray-400' : 'text-gray-500 hover:text-pink-500'} transition-colors relative`}
                aria-label="刷新推荐"
              >
                {isGeneratingRecommendations ? (
                  <RefreshCw size={16} className="animate-spin" />
                ) : (
                  <RefreshCw size={16} />
                )}
                <div className="flex items-center">
                  <Brain size={12} className="text-pink-400 ml-1" />
                </div>
              </button>
            </div>
          </div>
          
           <div className="text-sm text-gray-500 mb-4 italic flex items-center">
            <Brain size={12} className="mr-1 text-pink-400" />
            童话家根据你的喜好，为你准备了这些精彩故事
          </div>
          
          {/* 推荐故事列表 */}
          {isGeneratingRecommendations ? (
            // 推荐生成中状态
            <div className="space-y-4">
              {[1, 2].map(i => (
                <div key={i} className="bg-white rounded-xl p-4 border border-pink-100 animate-pulse">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="h-6 bg-pink-100 rounded w-1/2 mb-2"></div>
                      <div className="h-4 bg-pink-100 rounded w-full mb-3"></div>
                      <div className="flex space-x-3">
                        <div className="h-3 bg-pink-100 rounded w-16"></div>
                        <div className="h-3 bg-pink-100 rounded w-16"></div>
                      </div>
                    </div>
                    <div className="w-20 h-8 bg-pink-100 rounded-full"></div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
           <div className="space-y-4">
              {recommendedStories.map(story => (
                <div key={story.id} className="bg-white rounded-xl p-4 border border-pink-100 hover:border-pink-300 transition-all duration-300 shadow-sm hover:shadow-md card-gradient transform hover:translate-y-[-4px]">
                  <div className="flex items-start">
                    <div className="w-12 h-12 rounded-full bg-gradient-to-r from-pink-100 to-blue-100 flex items-center justify-center text-2xl shadow-sm mr-3 flex-shrink-0">
                      {story.theme === '魔法' ? '🔮' : story.theme === '星空' ? '🌌' : story.theme === '友谊' ? '👫' : story.theme === '海底' ? '🌊' : '📚'}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center">
                        <span className="text-xs bg-pink-100 text-pink-500 px-2 py-0.5 rounded-full flex items-center mr-2">
                          <Brain size={10} className="mr-1 text-pink-500" />
                          童话家推荐
                        </span>
                        <span className="text-xs bg-pink-100 text-pink-500 px-2 py-0.5 rounded-full flex items-center">
                          <Star size={10} className="mr-1 text-yellow-500" />
                          {story.relevance}%匹配度
                        </span>
                      </div>
                      <h3 className="text-lg font-semibold text-gray-800 mt-1">{story.title}</h3>
                      <p className="text-gray-500 text-sm mt-1 line-clamp-2">{story.description}</p>
                    </div>
                    <button onClick={() => readRecommendedStory(story)}
                      className="bg-gradient-to-r from-pink-500 to-blue-500 text-white text-sm px-3 py-1.5 rounded-full hover:opacity-90 transition-all duration-300 btn-gradient"
                    >
                      立即阅读
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      )}

      {/* 底部导航栏 */}
      <nav className="fixed bottom-0 left-0 right-0 bg-white/90 backdrop-blur-md border-t border-pink-100 h-16 flex justify-around items-center z-10 shadow-sm">
        <Link to="/home" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">🏠</span>
          <span className="text-xs mt-1">首页</span>
        </Link>
        <Link to="/generate" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">✨</span>
          <span className="text-xs mt-1">生成</span>
        </Link>
        <Link to="/collection" className="flex flex-col items-center justify-center text-pink-500">
          <span className="text-xl">❤️</span>
          <span className="text-xs mt-1">收藏</span>
        </Link>
        <Link to="/agent" className="flex flex-col items-center justify-center text-gray-500 hover:text-pink-500 transition-colors">
          <span className="text-xl">🤖</span>
          <span className="text-xs mt-1">智能助手</span>
        </Link>
      </nav>
      </div>
    </div>
  );
}